﻿using AutoMapper;
using HSGD.IRepository.BASE;
using HSGD.IServices.HSGD_Staff;
using HSGD.Model.Dtos.HSGD_Staff;
using HSGD.Model.Models.HSGD_Staff;
using HSGD.Services.BASE;

namespace HSGD.Services.HSGD_Staff;

public class EssayFormServices : BaseServices<RecPosApplicantEssayForm>, IEssayFormServices {
    private readonly IBaseRepository<RecPosApplicantEssayForm> _dal;
    IMapper _mapper;

    public EssayFormServices(IBaseRepository<RecPosApplicantEssayForm> dal, IMapper mapper) {
        this._dal = dal;
        base.BaseDal = dal;
        _mapper = mapper;
    }


    public async Task<RecPosApplicantEssayQueryDto> LoadEssayById(string rid, string pid) {
        string strSQL = $@"SELECT DISTINCT a.Recruit_System_ID,a.Person_System_ID,f.Name_First+' '+f.Name_Last AS labApplicantName, e.essay_title,d.job_code,b.content,b.create_dt,b.expire_dt,b.status,b.score,b.score_details,
b.iID as HFiID FROM dbo.rec_pos_applicant_interviewInfo a
INNER JOIN dbo.rec_position c ON c.recruit_system_id = a.Recruit_System_ID
INNER JOIN dbo.Position_Info d ON d.Position_System_ID = c.position_system_id
INNER JOIN dbo.Person f ON a.Person_System_ID=f.Person_System_ID
LEFT JOIN dbo.ref_interview_essay e ON e.jobcode=d.job_code
LEFT JOIN [dbo].[rec_pos_applicant_EssayForm] b ON b.Person_System_ID = a.Person_System_ID 
     AND CAST(GETDATE() AS DATE) BETWEEN CAST(b.create_dt AS DATE) AND b.expire_dt
WHERE a.Person_System_ID=@pid AND a.Recruit_System_ID=@rid";
        var data = await Db.SqlQueryable<RecPosApplicantEssayQueryDto>(strSQL)
            .AddParameters(new { rid, pid })
            .FirstAsync();
        return data;
    }


    public async Task<RecPosApplicantEssayForm> SaveDB(RecPosApplicantEssayDto input) {
        var data = _mapper.Map<RecPosApplicantEssayForm>(input);
        {
            data.Create_DT = DateTime.Now;
            data.Expired_DT = DateTime.Now.AddMonths(24);
        };

        return await Db.Insertable(data).ExecuteReturnEntityAsync();
    }
}
